<template>
  <div class="app-container">
    <!-- 筛选栏 -->
    <div v-show="showSearch">
      <!-- 搜索表单 -->
      <el-form :inline="true" ref="queryForm" size="small">
        <el-form-item label="职级" prop="grade_id">
          <el-select v-model="queryForm.grade" placeholder="请选择">
            <el-option v-for="item in gradeList" :key="item.id" :label="item.grade" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工种选择">
          <el-cascader size="small" v-model="queryForm.subjectId" :options="typeList" placeholder="选择工种" :props="{
            value: 'id',
            label: 'courseName',
            children: 'childrenList',
            expandTrigger: 'hover',
          }" :show-all-levels="false" clearable @change="handleCascaderChange3"></el-cascader>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="queryForm.className" placeholder="请输入班级名称" maxlength="30" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="queryClassList">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格上方按钮 -->
    <div>
      <div style="float: left; margin-bottom: 10px">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="preAdd">新增</el-button>
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="deleteList">批量删除</el-button>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="queryClassList" style="float: right"></right-toolbar>
    </div>
    <!-- 信息列表 -->
    <div style="float: left; width: 100%">
      <el-table border v-loading="listLoading" :header-cell-style="{ background: '#FAFAFA' }" :data="classList"
        @selection-change="handleSelectionChange" style="width: 100%" height="75vh">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="ID" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="eduClassInfo.className" label="班级">
        </el-table-column>
        <el-table-column prop="eduClassInfo.gradeName" label="职级">
        </el-table-column>
        <el-table-column prop="eduClassInfo.subjectName" label="工种">
        </el-table-column>
        <el-table-column prop="eduClassInfo.classSize" label="班级总人数">
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">{{
            scope.row.eduClassInfo.analysis != " "
            ? scope.row.eduClassInfo.analysis
            : "暂无"
          }}</template>
        </el-table-column>
        <el-table-column prop="eduClassInfo.openTime" label="开始时间">
        </el-table-column>
        <el-table-column prop="eduClassInfo.closeTime" label="结束时间">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="modify(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="medium" @click="deleteOne(scope.row)">
              删除
            </el-button>
            <el-button type="text" size="medium" @click="viewStudent(scope.row)">
              查看学员
            </el-button>
            <!-- 查看资源 -->
            <el-button type="text" size="medium" @click="viewResource(scope.row)">
              查看课件
            </el-button>
            <!-- <el-button type="text" size="medium" @click="viewRecord(scope.row)">
              学习统计
            </el-button> -->
            <el-button type="text" size="medium" @click="viewCourse(scope.row)">
              查看课程
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="width: 100%; text-align: center; margin-top: 10px">
        <el-pagination @size-change="sizeChange" @current-change="goto" :current-page="page.current"
          :page-sizes="[5, 10, 15, 20]" :page-size="page.size" layout="total, sizes, prev, pager, next, jumper"
          :total="page.total" background style="float: right">
        </el-pagination>
      </div>
    </div>
    <!-- 新增对话框 -->
    <el-dialog title="新增班级" :visible.sync="addDialog" width="30%" :before-close="handleClose">
      <el-form ref="form" :rules="rules" :model="addForm" label-width="80px">
        <el-row>
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="addForm.className" placeholder="请输入班级名称" maxlength="30" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="工种选择" prop="subjectId">
            <el-cascader size="small" v-model="addForm.subjectId" :options="typeList" placeholder="选择工种" :props="{
              value: 'id',
              label: 'courseName',
              children: 'childrenList',
              expandTrigger: 'hover',
            }" :show-all-levels="false" clearable @change="handleCascaderChange"></el-cascader>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="职级选择" prop="grade">
            <el-select v-model="addForm.grade" placeholder="请选择">
              <el-option v-for="item in gradeList" :key="item.id" :label="item.grade" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item label="开始时间" prop="openTime">
          <el-date-picker v-model="addForm.openTime" type="datetime" placeholder="选择起始时间"
            value-format="yyyy-MM-dd hh:mm:ss" @change="handleOpenTimeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="closeTime">
          <el-date-picker v-model="addForm.closeTime" type="datetime" placeholder="选择结束时间"
            value-format="yyyy-MM-dd hh:mm:ss" @change="handleCloseTimeChange">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-form-item label="备注" prop="analysis">
            <el-input type="textarea" v-model="addForm.analysis"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addClassInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="班级信息修改" :visible.sync="modifyDialog" width="30%" :before-close="handleClose">
      <el-form ref="form" :rules="rules" :model="modifyForm" label-width="80px">
        <el-row>
          <el-form-item label="班级名称" prop="className">
            <el-input v-model="modifyForm.className" placeholder="请输入班级名称" maxlength="30" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="工种选择" prop="subjectId">
            <el-cascader size="small" v-model="modifyForm.subjectId" :options="typeList" placeholder="选择工种" :props="{
              value: 'id',
              label: 'courseName',
              children: 'childrenList',
              expandTrigger: 'hover',
            }" :show-all-levels="false" clearable @change="handleCascaderChange2"></el-cascader>
          </el-form-item>
        </el-row>
        <el-form-item label="职级选择" prop="grade">
          <el-select v-model="modifyForm.grade" placeholder="请选择">
            <el-option v-for="item in gradeList" :key="item.id" :label="item.grade" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="openTime">
          <el-date-picker v-model="modifyForm.openTime" type="datetime" placeholder="选择起始时间"
            value-format="yyyy-MM-dd hh:mm:ss" @change="handleOpenTimeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="closeTime">
          <el-date-picker v-model="modifyForm.closeTime" type="datetime" placeholder="选择结束时间"
            value-format="yyyy-MM-dd hh:mm:ss" @change="handleCloseTimeChange">
          </el-date-picker>
        </el-form-item>
        <el-row>
          <el-form-item label="备注" prop="analysis">
            <el-input type="textarea" v-model="modifyForm.analysis"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdate()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import {
  addClass,
  deleteClass,
  updateClass,
  queryList,
} from "@/api/class/classList";
import { getAllCourse } from "@/api/edu/course";
import { mapGetters } from "vuex";
import { getCategory, getClassList } from "@/api/classification";
import { getGrade } from "@/api/edu/course";

export default {
  //班级列表
  name: "Class",
  computed: {
    ...mapGetters(["companyId"]),
  },

  data: function () {
    return {
      //表格加载遮罩
      listLoading: "false",
      //课程列表
      courseList: [],
      //搜索表单
      queryForm: {
        className: "",
        subjectId: "",
        grade: "",
      },
      //分页设置
      page: {
        current: 1,
        total: 0,
        size: 10,
      },
      //班级列表
      classList: [],
      //批量删除列表
      selectList: [],
      //新增试卷对话框
      addDialog: false,
      //新增试卷的表单
      addForm: {},
      //修改试卷的对话框
      modifyDialog: false,
      //修改试卷的id
      modifyId: "",
      //修改试卷的表单
      modifyForm: {},
      //是否显示搜索表单
      showSearch: true,
      //表单验证
      rules: {
        className: [
          { required: true, message: "请输入班级名称", trigger: "blur" },
        ],
        subjectId: [
          { required: true, message: "请选择工种", trigger: "blur" },
        ],
        grade: [
          { required: true, message: "请选择职级", trigger: "blur" },
        ],
      },
      //类别列表
      typeList: [],
      // 班级下拉列表
      classNameList: [],
      // 职级列表
      gradeList: []
    };
  },
  created: function () {
    this.queryClassList();
    //查询所有课程列表
    getAllCourse(this.companyId).then((res) => {
      const data = res.data;
      this.courseList = data.list;
    });
    this.getCategoryList(this.companyId);
    this.getClassNameList(this.companyId);
    this.getGradeList();
  },
  methods: {
    //查找班级列表
    queryClassList: function () {
      this.listLoading = true;
      //console.log(this.queryForm);
      //表格数据
      queryList(this.queryForm, this.page.current, this.page.size).then(
        (res) => {
          const data = res.data;
          //console.log(data)
          this.page.total = data.total;
          // 对data.resList进行遍历处理
          data.resList.forEach((item) => {
            // 将GradeName和subjectName复制给eduClassInfo
            item.eduClassInfo.gradeName = item.gradeName;
            item.eduClassInfo.subjectName = item.subjectName;
          });
          this.classList = data.resList;
          //console.log(this.classList);
          this.listLoading = false;
        }
      );
    },
    //查询所有的职级
    getGradeList () {
      getGrade().then((res) => {
        if (res.success) {
          this.gradeList = res.data.resList;
          //console.log(this.gradeList)
        }
      });
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryForm = {
        className: "",
        subjectId: "",
        grade: "",
      };
      this.queryClassList();
    },
    //新增预处理
    preAdd () {
      this.addForm = {
        className: "",
        analysis: "",
        classSize: 0,
        openTime: "",
        closeTime: "",
        grade: "",
        subjectId: "",
      };
      if (this.$refs["form"] !== undefined) {
        this.$refs["form"].resetFields();
      }
      this.addDialog = true;
    },
    //新增班级
    addClassInfo () {
      //console.log(this.addForm)
      if (this.addForm.className == "" || this.addForm.subjectId == "" || this.addForm.grade == "") {
        this.$message({
          message: "请填写必要信息",
          type: "warning",
        });
      } else {
        addClass(this.addForm).then((res) => {
          if (res.success == true) {
            this.$message({
              message: "提交成功",
              type: "success",
            });
            this.queryClassList();
            this.addDialog = false;
          } else {
            this.$message({
              message: "提交失败",
              type: "error",
            });
          }
        });
        // console.log(this.addForm);
      }
    },
    //关闭对话框
    handleClose (done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => { });
    },
    //选择删除的id列表
    handleSelectionChange: function (val) {
      this.selectList = val;
    },
    //删除单个班级
    deleteOne: function (row) {
      var self = this;
      this.$confirm("此操作将删除该班级, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = []; //删除列表
          idArray.push(row.id);
          self.deleteAjax(idArray);
        })
        .catch(() => { });
    },
    //删除多份试卷
    deleteList: function () {
      if (this.selectList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      var self = this;
      this.$confirm("此操作将删除选中的所有试卷, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = [];
          self.selectList.forEach(function (item, index) {
            idArray.push(item.id);
          });
          self.deleteAjax(idArray);
        })
        .catch(() => { });
    },
    //删除的Ajax请求
    deleteAjax: function (idArray) {
      var that = this;
      deleteClass(idArray).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          that.queryClassList();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    //编辑预处理
    modify (row) {
      //console.log(row)
      this.modifyForm = row.eduClassInfo;
      this.modifyForm.id = row.id;
      this.modifyDialog = true;
      // 在gradeList中找到对应row.gradeName的值的序号
      let index;
      this.gradeList.forEach(item => {
        if (item.grade === row.gradeName) index = item.id;
      });
      this.modifyForm.grade = index;
    },
    //提交修改
    submitUpdate () {
      let that = this;
      if (
        this.modifyForm.className == "" ||
        this.modifyForm.courseVideoId == "" ||
        this.modifyForm.grade == ""
      ) {
        this.$message({
          message: "请填写必要信息",
          type: "warning",
        });
      } else {
        updateClass(this.modifyForm).then((res) => {
          if (res.success == true) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            that.queryClassList();
            that.modifyDialog = false;
          } else {
            this.$message({
              message: "修改失败",
              type: "error",
            });
          }
        });
      }
    },
    //查看班级学员
    viewStudent: function (row) {
      this.$router.push({
        name: "ClassStudent",
        query: {
          id: row.id,
          courseVideoId: row.eduClassInfo.courseVideoId,
          grade: row.eduClassInfo.grade,
          subjectId: row.eduClassInfo.subjectId,
        },
      });
    },
    // 查看课件
    viewResource: function (row) {
      this.$router.push({
        name: "ClassResource",
        query: {
          classId: row.id,
        },
      });
    },
    // 查看课程
    viewCourse: function (row) {
      this.$router.push({
        name: "ClassCourse",
        query: {
          classId: row.id,
        },
      });
    },
    //跳转页面
    goto: function (current) {
      this.page.current = current;
      this.queryClassList();
    },
    //页码改变
    sizeChange: function (size) {
      this.page.size = size;
      this.queryClassList();
    },

    //获取类别列表
    getCategoryList () {
      getCategory(0, this.companyId).then((res) => {
        const data = res.data;
        this.typeList = this.deleteChildren(data.resList);
        // console.log(this.typeList);
      });
    },
    //删除类别列表中的空childrenList[]
    deleteChildren (arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].childrenList) {
          if (childs[i].childrenList.length) {
            this.deleteChildren(childs[i].childrenList);
          } else {
            delete childs[i].childrenList;
          }
        }
      }
      return arr;
    },

    // 新增下拉框绑定工种子id
    handleCascaderChange (selectedValues) {
      // 获取最终选定的 children 的 id
      const finalSelectedId = selectedValues[selectedValues.length - 1];
      // 将其绑定到 addForm.subjectId
      this.addForm.subjectId = finalSelectedId;
    },
    // 编辑下拉框绑定工种子id
    handleCascaderChange2 (selectedValues) {
      // 获取最终选定的 children 的 id
      const finalSelectedId = selectedValues[selectedValues.length - 1];
      // 将其绑定到 modifyForm.subjectId
      this.modifyForm.subjectId = finalSelectedId;
    },
    // 筛选下拉框绑定工种子id
    handleCascaderChange3 (selectedValues) {
      // 获取最终选定的 children 的 id
      const finalSelectedId = selectedValues[selectedValues.length - 1];
      // 将其绑定到 modifyForm.subjectId
      this.queryForm.subjectId = finalSelectedId;
    },

    // 获取班级下拉列表
    getClassNameList () {
      getClassList(this.companyId).then((res) => {
        this.classNameList = res.data.rows;
      });
    },
    handleOpenTimeChange (value) {
      this.modifyForm.openTime = new Date(value);
      // 打印openTime的类型
      //console.log(this.modifyForm.openTime instanceof Date)
    },
    handleCloseTimeChange (value) {
      this.modifyForm.closeTime = new Date(value);
    }
  },
};
</script>
  
<style scoped></style>
  